package cn.display.pixelworksx7.threadpool;


import io.netty.util.concurrent.DefaultThreadFactory;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class SystemThreadPool {
    private static ExecutorService executorService = null;

    /**
     * 通过主键删除数据
     *
     * @return 操作线程池
     */
    public static ExecutorService getExecutorService() {
        // 不为空说明已初始化 直接返回
        if (executorService != null) {
            return executorService;
        } else {
            // 初始化返回
            return initExecutorService();
        }
    }

    private static final int DEFAULT_THREAD_SIZE = 16;
    private static final int DEFAULT_QUEUE_SIZE = 10240;

    private static final String poolName = "SystemThreadPool";

    private static ExecutorService initExecutorService() {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                DEFAULT_THREAD_SIZE,// 线程池的核心线程数量
                DEFAULT_THREAD_SIZE,// 线程池的最大线程数
                300, // 当线程数大于核心线程数时，多余的空闲线程存活的最长时间
                TimeUnit.SECONDS,// 时间单位
                new ArrayBlockingQueue<>(DEFAULT_QUEUE_SIZE), // 任务队列，用来存储等待执行任务的队列
                new DefaultThreadFactory(poolName), // 线程工厂，用来创建线程，一般默认即可
                new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略，当提交的任务过多而不能及时处理时，我们可以定制策略来处理任务
        );
        return threadPoolExecutor;
    }
}
